<?php

namespace App\Http\Controllers\Api\Merchant;

use App\Enterprise;
use App\EnterpriseAdmin;
use App\EnterpriseApply;
use App\EnterpriseWechatPayment;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\MerchantManager;
use App\Http\Services\UserManager;
use App\Merchant;
use App\MerchantStaff;
use App\Permission;
use App\Role;
use App\User;
use App\VerifyPhone;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Cookie;
use Hash;
use Illuminate\Support\Facades\DB;

class AuthController extends Controller
{
    public function signUp(Request $request){
        $username                = $request->input('username') ?? '';
        $password                = $request->input('password') ?? '';
        $phone                   = $request->input('phone') ?? '';
        $verifyCode              = $request->input('verify_code') ?? '';

        if($phone == '')
            return response()->json(['level' => 'error','message' => '请输入手机号']);

        $phoneVerification = CommonManager::phoneVerification($phone);
        if(!$phoneVerification)
            return response()->json(['level' => 'error','message' => '手机号格式不正确']);

        $phoneExists = User::wherePhone($phone)->whereIn('role',[2,3])->first();
        if($phoneExists)
            return response()->json(['level' => 'error','message' => '手机号已被注册']);

        $verifyCodeByPhone = VerifyPhone::wherePhone($phone)->whereVerifyCode($verifyCode)->first();
        if(!$verifyCodeByPhone || $verifyCodeByPhone->created_at->timestamp + 60 * 15 < time()){
            return response()->json(['level' => 'error','message' => '验证码错误或已过期！']);
        }
        $verifyCodeByPhone -> delete();

        if($username == '')
            return response()->json(['level' => 'error','message' => '请输入账号']);

        $userExists = User::whereUsername($username)->first();
        if($userExists)
            return response()->json(['level' => 'error','message' => '该账号已被注册']);

        if($password == '')
            return response()->json(['level' => 'error','message' => '请输入密码']);

        DB::beginTransaction();
        try{
            $newMerchantUser = MerchantManager::signUp($username,$password,$phone);

            $role = Role::whereName('merchant_user')->first();
            if($role){
                DB::table('role_user')->insert(['user_id' => $newMerchantUser->id,'role_id' => $role->id]);
            }

            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return response()->json(['level' => 'error','message' => $e->getMessage()]);
        }

        return response()->json(['level' => 'success','message' => '注册成功','data' => $newMerchantUser]);
    }

    /**
     * 校验账号是否可用
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function usernameVerify(Request $request){
        $username = $request->input('username') ?? '';

        $userExists = User::whereUsername($username)->first();
        if($userExists){
            return response()->json(['level' => 'error','message' => '账号已存在','data' => 'no']);
        }else{
            return response()->json(['level' => 'success','message' => '账号可用','data' => 'yes']);
        }
    }

    /**
     * 获取商家审核状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEnterpriseReviewStatus(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if($enterpriseInfo){
            $status = 'yes';
            $enterpriseAdminUserIds = EnterpriseAdmin::whereEnterpriseId($enterpriseInfo->id)->pluck('user_id');

//            $enterpriseApply = EnterpriseApply::whereIn('user_id',$enterpriseAdminUserIds)->orderByDesc('created_at')->first();
            $enterpriseApply = (object)['review' => 1,'review_name' => '审核已通过'];
        }else{
            $status = 'no';
            $enterpriseApply = EnterpriseApply::whereUserId($MerchantUser->id)->orderByDesc('created_at')->first();

            if(!$enterpriseApply)
                return response()->json(['level' => 'error','message' => '未提交审核']);

            $enterpriseApply->business_license_img_url = FileManager::getImgUrl($enterpriseApply->business_license_img_id);

            if($enterpriseApply->review == 1){
                $enterpriseApply->review_name = '审核已通过';
            }elseif($enterpriseApply->review == 2){
                $enterpriseApply->review_name = '审核已拒绝';
            }else{
                $enterpriseApply->review_name = '审核处理中';
            }

        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $enterpriseApply,'status' => $status]);
    }

    /**
     * 商家审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function enterpriseReview(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $name                    = $request->input('name') ?? '';
        $contactPerson           = $request->input('contact_person') ?? '';
        $contact                 = $request->input('contact') ?? '';
        $companyName             = $request->input('company_name') ?? '';
        $UnifiedSocialCreditCode = $request->input('Unified_social_credit_code') ?? '';
        $businessLicenseImgId    = $request->input('business_license_img_id') ?? 0;
        $legalPerson             = $request->input('legal_person') ?? '';

        if($companyName == '')
            return response()->json(['level' => 'error','message' => '请输企业名称']);

        if($legalPerson == '')
            return response()->json(['level' => 'error','message' => '请填写法人名称']);

        if($UnifiedSocialCreditCode == '')
            return response()->json(['level' => 'error','message' => '请填写统一社会信用代码']);

        $uniformSocialCreditCodeVerification = CommonManager::uniformSocialCreditCodeVerification($UnifiedSocialCreditCode);
        if(!$uniformSocialCreditCodeVerification)
            return response()->json(['level' => 'error','message' => '统一社会信用代码格式错误']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if($enterpriseInfo){
            $merchantExist = Enterprise::whereUnifiedSocialCreditCode($UnifiedSocialCreditCode)->where('id','<>',$enterpriseInfo->id)->first();
            if($merchantExist)
                return response()->json(['level' => 'error','message' => '统一社会信用代码已被使用']);

            $enterpriseUserIds = MerchantManager::getMerchantAdminById($enterpriseInfo->id);

            $enterpriseApply = EnterpriseApply::where('user_id',$enterpriseUserIds)->whereReview(0)->first();
            if($enterpriseApply)
                return response()->json(['level' => 'error','message' => '正在审核中，请勿重复提交']);
        }else{
            $merchantExist = Enterprise::whereUnifiedSocialCreditCode($UnifiedSocialCreditCode)->first();
            if($merchantExist)
                return response()->json(['level' => 'error','message' => '统一社会信用代码已被使用']);

            $enterpriseApply = EnterpriseApply::whereUserId($MerchantUser->id)->whereReview(0)->first();
            if($enterpriseApply)
                return response()->json(['level' => 'error','message' => '正在审核中，请勿重复提交']);
        }

        DB::beginTransaction();
        try{
            $enterpriseApply = new EnterpriseApply();
            $enterpriseApply->user_id                       = $MerchantUser->id;
            $enterpriseApply->name                          = $name;
            $enterpriseApply->contact                       = $contact;
            $enterpriseApply->contact_person                = $contactPerson;
            $enterpriseApply->company_name                  = $companyName;
            $enterpriseApply->legal_person                  = $legalPerson;
            $enterpriseApply->Unified_social_credit_code    = $UnifiedSocialCreditCode;
            $enterpriseApply->business_license_img_id       = $businessLicenseImgId;
            $enterpriseApply->review                        = 0;
            $enterpriseApply->save();

            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return response()->json(['level' => 'error','message' => '提交失败' . $e->getMessage()]);
        }

        return response()->json(['level' => 'success','message' => '提交成功','data' => $enterpriseApply]);
    }

    public function signIn(Request $request){
        $username     = $request->get('username');
        $password     = $request->get('password');
        $phone        = $request->input('phone') ?? '';
        $verifyCode   = $request->input('verify_code') ?? '';
        $type         = $request->input('type') ?? 'username';

        if($type == 'phone'){
            if($phone == '')
                return response()->json(['level' => 'error','message' => '请输入手机号']);

            $phoneVerification = CommonManager::phoneVerification($phone);
            if(!$phoneVerification)
                return response()->json(['level' => 'error','message' => '手机号格式不正确']);

            $verifyCodeByPhone = VerifyPhone::wherePhone($phone)->whereVerifyCode($verifyCode)->first();
            if(!$verifyCodeByPhone || $verifyCodeByPhone->created_at->timestamp + 60 * 15 < time()){
                return response()->json(['level' => 'error','message' => '验证码错误或已过期！']);
            }
            $verifyCodeByPhone -> delete();

            $user = User::wherePhone($phone)->whereIn('role',[2,3])->first();
            if(!$user)
                return response()->json(['level' => 'error','message' => '该手机号尚未注册！']);
        }else{
            /** @var User $isUser */
            $isUser = User::whereUsername(trim($username))->first();
            if(!$isUser)
                return response()->json(['level' => 'error','message' => '该用户不存在']);

            /** @var User $user */
            $user = MerchantManager::signInByUsername($username,$password,0);
            if(!$user)
                return response()->json(['level'=>'error','message'=>'帐号或密码错误！']);
        }

        if($user->role != 2 && $user->role != 3)
            return response()->json(['level' => 'error','message' => '无权限登录']);

        $merchantAdmin = Role::whereName('merchant_admin')->first();
        if($merchantAdmin){
            $merchantAdminExists = DB::table('role_user')->where('user_id',$user->id)->where('role_id',$merchantAdmin->id)->first();
        }else{
            $merchantAdminExists = null;
        }

        if(!$user->can('enterprise_sign_in') && !$merchantAdminExists)
            return response()->json(['level' => 'error','message' => '没有登录权限','data'=>'no_permission']);

        if($user->status != 1)
            return response()->json(['level' => 'error','message' => '该账号已被锁定']);

        $userMark = $user->user_key;

        $token = CryptoJSAES::encrypt($userMark,env('AES_KEY'));

        $cookie = Cookie::forever("merchant_token", $token);

        return response()->json(['level' => 'success','message' => trans("登录成功！"),'data' => $token])->withCookie($cookie);
    }

    /**
     * 修改密码
     * @param Guard $guard
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changePassword(Guard $guard,Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $oldPassword = $request->get('oldpassword');
        $newpassword = $request->get('newpassword');
        $repass   = $request->get('repass');

        if(is_null($oldPassword) && $oldPassword == '')
            return response()->json(['level' => 'error','message' => '请输入原密码']);

        if(is_null($newpassword) && $newpassword == '')
            return response()->json(['level' => 'error','message' => '请输入新密码']);

        if(is_null($repass) && $repass == '')
            return response()->json(['level' => 'error','message' => '请再次输入新密码']);

        if(!Hash::check($oldPassword,$MerchantUser->password))
            return response()->json(['level'=>'error','message'=>'原密码不匹配！']);

        if(Hash::check($newpassword,$MerchantUser->password))
            return response()->json(['level'=>'error','message'=>'原密码与新密码不能一致！']);

        if($newpassword != $repass)
            return response()->json(['level'=>'error','message' => '两次密码不一致！']);

        $MerchantUser->password = bcrypt($newpassword);
        $MerchantUser->save();

        $loginOut = Cookie::forget('merchant_token');

        return response()->json(['level'=>'success','message'=>trans("密码修改成功！"),'data' => 'no_login'])->withCookie($loginOut);
    }

    /**
     * 退出登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function loginOut(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $cookie = Cookie::forget('merchant_token');

        return response()->json(['level' => 'success','message' => '退出成功','data' => 'no_login'])->withCookie($cookie);
    }

    /**
     * 获取商户管理员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMerchantUserInfo(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        $MerchantUser->enterprise_info = $enterpriseInfo;
        $enterpriseInfo->business_license_img_url = FileManager::getImgUrl($enterpriseInfo->business_license_img_id);

        $token = CryptoJSAES::encrypt($MerchantUser->user_key,env('AES_KEY'));

        $MerchantUser->merchant_token = $token;

        $merchantAdmin = Role::whereName('merchant_admin')->first();
        if($merchantAdmin){
            $merchantAdminExists = DB::table('role_user')->where('user_id',$MerchantUser->id)->where('role_id',$merchantAdmin->id)->first();
        }else{
            $merchantAdminExists = null;
        }

        $module = [];

        //数据统计
        $module['data_summary'] = 0;
        if($MerchantUser->can('data_summary_select') || $merchantAdminExists)
            $module['data_summary'] = 1;

        //用户列表
        $module['enterprise_user'] = 0;
        if($MerchantUser->can('enterprise_user_select') || $merchantAdminExists)
            $module['enterprise_user'] = 1;

        //商家信息
        $module['enterprise_info'] = 0;
        if($MerchantUser->can('enterprise_info_select') || $merchantAdminExists)
            $module['enterprise_info'] = 1;

        //小程序授权管理
        $module['authorize_info'] = 0;
        if($MerchantUser->can('authorize_info_select') || $merchantAdminExists)
            $module['authorize_info'] = 1;

        //门店列表
        $module['merchant'] = 0;
        if($MerchantUser->can('merchant_select') || $merchantAdminExists)
            $module['merchant'] = 1;

        //商品列表
        $module['goods'] = 0;
        if($MerchantUser->can('goods_select') || $merchantAdminExists)
            $module['goods'] = 1;

        //商家审核列表
        $module['goods_apply'] = 0;
        if($MerchantUser->can('goods_apply_select') || $merchantAdminExists)
            $module['goods_apply'] = 1;

        //订单列表
        $module['order'] = 0;
        if($MerchantUser->can('order_select') || $merchantAdminExists)
            $module['order'] = 1;

        //交易流水列表
        $module['money_change'] = 0;
        if($MerchantUser->can('money_change_select') || $merchantAdminExists)
            $module['money_change'] = 1;

        //促销规则列表
        $module['discount_sales_rule'] = 0;
        if($MerchantUser->can('discount_sales_rule_select') || $merchantAdminExists)
            $module['discount_sales_rule'] = 1;

        //banner列表
        $module['banner'] = 0;
        if($MerchantUser->can('banner_select') || $merchantAdminExists)
            $module['banner'] = 1;

        //功能区列表
        $module['button'] = 0;
        if($MerchantUser->can('button_select') || $merchantAdminExists)
            $module['button'] = 1;

        //专区列表
        $module['area'] = 0;
        if($MerchantUser->can('area_select') || $merchantAdminExists)
            $module['area'] = 1;

        //关于我们
        $module['about_us'] = 0;
        if($MerchantUser->can('about_us_select') || $merchantAdminExists)
            $module['about_us'] = 1;

        //角色列表
        $module['role'] = 0;
        if($MerchantUser->can('role_select') || $merchantAdminExists)
            $module['role'] = 1;

        //管理员列表
        $module['admin'] = 0;
        if($MerchantUser->can('admin_select') || $merchantAdminExists)
            $module['admin'] = 1;

        $MerchantUser->module_list = $module;

        return response()->json(['level' => 'success','message' => '获取成功','data' => $MerchantUser]);
    }

    /**
     * 获取管理员列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function adminList(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        $merchantUserIds = EnterpriseAdmin::whereEnterpriseId($enterpriseInfo->id)->pluck('user_id');

        $adminUserList = User::whereIn('id',$merchantUserIds)->whereRole(2);

        $arr['total'] = $adminUserList->count();

        if($MerchantUser->hasRole("virtual_admin")){
            $adminUserList = $adminUserList->whereIn("id",[$MerchantUser->id])->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        }else{
            $adminUserList = $adminUserList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        }

        if(count($adminUserList) > 0){
            foreach($adminUserList as $adminUser){
                $UserRole = DB::table('role_user')->where('user_id',$adminUser->id)->first();
                if($UserRole){
                    /** @var Role $role */
                    $role = Role::whereId($UserRole->role_id)->first();
                    if($role){
                        $adminUser->role_name = $role->display_name;
                    }else{
                        $adminUser->role_name = null;
                    }
                }else{
                    $adminUser->role_name = null;
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $adminUserList,'page_info' => $arr]);
    }

    /**
     * 管理员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function adminSet(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisAdminUser = User::whereRole(2)->whereId($id)->first();
        if($thisAdminUser){
            $roleUsers = DB::table('role_user')->where('user_id',$thisAdminUser->id)->get();
            $roleIds = array();
            if(count($roleUsers) > 0){
                foreach($roleUsers as $roleUser){
                    /** @var Role $role */
                    $roleList = Role::whereId($roleUser->role_id)->get();
                    if(count($roleList) > 0){
                        foreach($roleList as $role){
                            $roleObj = $role->id;
                            array_push($roleIds,$roleObj);
                        }
                    }

                }
            }

            $thisAdminUser->role_id = $roleIds;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $thisAdminUser,'id' => $id]);
    }

    /**
     * 添加管理员用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setAdmin(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $username   = $request->get('username');
        $password   = $request->get('password');
        $roleIds    = $request->get('role_id');
        $adminName  = $request->get('admin_name');
        $phone      = $request->get('phone');
//        $repass   = $request->get('repass');
        $status     = !is_null($request->get('status')) && $request->get('status') != '' ? $request->get('status') : 0;
        $id         = !is_null($request->get('id')) ? $request->get('id') : 0;

        if(!is_array($roleIds) || (is_array($roleIds) && count($roleIds) <= 0))
            return response()->json(['level' => 'error','message' => '角色的数据格式不对']);

        /** @var User $hasUser */
        $hasUser = User::whereUsername(trim($username))->first();

        /** @var User $thatUser */
        $thatUser = User::whereId($id)->first();

        if($thatUser && ($hasUser && $thatUser->id != $hasUser->id))
            return response()->json(['level' => 'error','message' => '当前管理员账号已存在']);

        if($phone != '' && !is_null($phone)){
            $phoneVerification = CommonManager::phoneVerification(trim($phone));
            if(!$phoneVerification)
                return response()->json(['level' => 'error','message' => '手机号格式不正确']);

            $isPhone = User::wherePhone(trim($phone))->whereIn('role',[2,3])->first();

            if($thatUser && ($isPhone && $thatUser->id != $isPhone->id))
                return response()->json(['level' => 'error','message' => '当前手机号已被使用']);
        }

        if(!$thatUser){
            if($hasUser)
                return response()->json(['level'=>'error','message' => '当前管理员账号已存在']);

            if($phone != '' && !is_null($phone)) {
                if ($isPhone)
                    return response()->json(['level' => 'error', 'message' => '当前手机号已被使用']);
            }
//            if(is_null($repass) && $repass == '')
//                return response()->json(['level' => 'error','message' => '请再次输入密码']);
//
//            if($password != $repass)
//                return response()->json(['level'=>'error','message' => '两次密码不一致！']);

            $thatUser = new User();
            $thatUser->user_key = md5($password . rand(1000,9999).time());
        }

        $thatUser->username    = $username;
        $thatUser->phone       = $phone;
        $thatUser->admin_name  = $adminName;

        if(!empty($password))
            $thatUser->password    = bcrypt($password);

        $thatUser->role        = 2;
        $thatUser->reg_ip      = $request->ip();
        $thatUser->reg_time    = date("Y-m-d H:i:s",time());
        $thatUser->status      = $status;
        $thatUser->save();

        $merchantStaff = EnterpriseAdmin::whereUserId($thatUser->id)->first();
        if(!$merchantStaff){
            $newMerchantStaff = new EnterpriseAdmin();
            $newMerchantStaff->user_id          = $thatUser->id;
            $newMerchantStaff->enterprise_id    = $enterpriseInfo->id;
            $newMerchantStaff->save();
        }

        DB::table('role_user')->where('user_id',$thatUser->id)->delete();

        foreach($roleIds as $roleId){
            $role = Role::whereId($roleId)->first();
            if($role){
                DB::table('role_user')->insert(['user_id' => $thatUser->id,'role_id' => $roleId]);
            }
        }

        return response()->json(['level'=>'success','message'=>'添加成功','data'=>$thatUser]);
    }

    /**
     * 改变管理员状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeAdminStatus(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var User $thatUser */
        $thatUser = User::whereId($id)->first();
        if(!$thatUser)
            return response()->json(['level' => 'success','message' => '管理员不存在']);

        $merchantAdminExists = null;
        $merchantAdmin = Role::whereName('merchant_admin')->first();
        if($merchantAdmin){
            $merchantAdminExists = DB::table('role_user')->where('user_id',$thatUser->id)->where('role_id',$merchantAdmin->id)->first();
        }

        if($merchantAdminExists)
            return response()->json(['level' => 'error','message' => '超级管理员不能修改']);

        if($thatUser->status == 1){
            $thatUser->status = 0;
        }else{
            $thatUser->status = 1;
        }

        $thatUser->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $thatUser]);
    }

    /**
     * 删除管理员用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delAdmin(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var User $thatUser */
        $thatUser = User::whereId($id)->first();
        if(!$thatUser)
            return response()->json(["level"=>"error","message"=>"该管理员不存在！"]);

        $enterpriseAdmin = EnterpriseAdmin::whereEnterpriseId($enterpriseInfo->id)->first();
        if($enterpriseAdmin){
            if($thatUser->id == $enterpriseAdmin->user_id)
                return response()->json(['level' => 'error','message' => '该管理员无法删除']);
        }

        $thatUser->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatUser]);
    }

    /**
     * 获取角色列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function roleList(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        $roles = Role::whereEnterpriseId($enterpriseInfo->id)->whereType('enterprise')->orWhere(function ($query){
            $query->where('name','merchant_admin')->orWhere('name','merchant_user');
        });

        $arr['total'] = $roles->count();

        $roles = $roles->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $roles,'page_info' => $arr]);
    }

    /**
     * 角色信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function roleSet(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var Role $role */
        $role = Role::whereId($id)->first();
        if($role){
            $permissionRoles = DB::table('permission_role')->where('role_id',$role->id)->get();
            $permissionIds = array();
            if(count($permissionRoles) > 0){
                foreach($permissionRoles as $permissionRole){
                    /** @var Permission $permission */
                    $permissionList = Permission::whereId($permissionRole->permission_id)->get();
                    if(count($permissionList) > 0){
                        foreach($permissionList as $permission){
                            $permissionObj = $permission->id;
                            array_push($permissionIds,$permissionObj);
                        }
                    }

                }
            }

            $role->permission_id = $permissionIds;
        }

        /** @var Permission $permission */
        $permissions = Permission::whereType('enterprise')->get();
        $permissionArr = array();
        if(count($permissions) > 0){
            foreach($permissions as $permission){
                $permissionInfo = (object)['id' => $permission->id,'permission' => $permission->display_name];
                array_push($permissionArr,$permissionInfo);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $role,'permission_list' => $permissionArr]);
    }

    /**
     * 添加角色
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setRole(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $name          = $request->get('name') ?? '';
        $displayName   = $request->get('display_name');
        $description   = $request->get('description');
        $id            = !is_null($request->get('id')) ? $request->get('id') : 0;
        $permissionIds = $request->get('permission_id');

        if(empty($displayName))
            return response()->json(['level' => 'error','message' => '请输入角色名']);

        $isName = Role::whereEnterpriseId($enterpriseInfo->id)->whereType('enterprise')->whereDisplayName($displayName)->first();

        $newRole = Role::whereId($id)->first();

        if($isName && ($newRole && $isName->id != $newRole->id))
            return response()->json(['level' => 'error','message' => '该角色名已存在']);

        if(!$newRole){
            if($isName)
                return response()->json(['level' => 'error','message' => '该角色名已存在']);

            $newRole = new Role();
        }else{
            if(in_array($newRole->name,['system_admin','merchant_admin','merchant_user']))
                return response()->json(['level' => 'error','message' => '内置角色无法编辑']);
        }

        $newRole->enterprise_id           = $enterpriseInfo->id;
        if(!is_null($name))$newRole->name = $name;
        if(!is_null($displayName))$newRole->display_name = $displayName;
        if(!is_null($description))$newRole->description = $description;
        $newRole->type                                  = 'enterprise';
        $newRole->save();

        DB::table('permission_role')->where('role_id',$newRole->id)->delete();

        if(is_array($permissionIds)){
            if(count($permissionIds) > 0){
                foreach($permissionIds as $permissionId){
                    DB::table('permission_role')->insert(['role_id' => $newRole->id,'permission_id' => $permissionId]);
                }
            }
        }else{
            return response()->json(['level' => 'error','message' => '权限的数据格式不对']);
        }

        return response()->json(['level' => 'success','message' => '设置成功']);
    }

    /**
     * 删除角色
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delRole(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisRole = Role::whereId($id)->first();
        if(!$thisRole)
            return response()->json(['level' => 'error','message' => '该角色不存在']);

        if(in_array($thisRole->name,['system_admin','merchant_admin','merchant_user']))
            return response()->json(['level' => 'error','message' => '内置角色无法删除']);

        $thisRole = DB::table('roles')->where('id',$id)->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thisRole]);
    }

    /**
     * 获取权限列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function permissionsList(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        $permissions = Permission::whereType('enterprise');

        $arr['total'] = $permissions->count();

        $permissions = $permissions->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $permissions,'page_info' => $arr]);
    }

    /**
     * 获取小程序支付方式
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getWxappPayment(Request $request){
        return response()->json(['level'=>'error','message'=>'请使用新的接口']);
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $enterpriseWechantPayment = EnterpriseWechatPayment::whereEnterpriseId($enterpriseInfo->id)->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $enterpriseWechantPayment]);
    }

    /**
     * 设置小程序支付方式
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setWxappPayment(Request $request){
        return response()->json(['level'=>'error','message'=>'请使用新的接口']);
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $merchantId = $request->input('merchant_id') ?? '';
        $key        = $request->input('key') ?? '';

        if($merchantId == '')
            return response()->json(['level' => 'error','message' => '请填写商户号']);

        if($key == '')
            return response()->json(['level' => 'error','message' => '请填写api密钥']);

        $enterpriseWechantPayment = EnterpriseWechatPayment::whereEnterpriseId($enterpriseInfo->id)->first();
        if(!$enterpriseWechantPayment)
            $enterpriseWechantPayment = new EnterpriseWechatPayment();

        $enterpriseWechantPayment->enterprise_id = $enterpriseInfo->id;
        $enterpriseWechantPayment->merchant_id   = $merchantId;
        $enterpriseWechantPayment->key           = $key;
        $enterpriseWechantPayment->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $enterpriseWechantPayment]);
    }
}
